<template>
  <div class="city-select">
    <el-cascader
      v-model="value"
      :options="cityList"
      @active-item-change="handleItemChange"
      :props="props"
      :clearable="true"
      separator="-"
      placeholder="请选择"
    ></el-cascader>
  </div>
</template>

<script>
  import {fetchCitiesList} from '@/api/web/dictionary'

  export default {
    watch:{
      value(newVal){
        this.$emit('childByValue', newVal)
      }
    },
    data() {
      return {
        value: [],
        cityList: [],
        props: {
          value: 'cityCode',
          label: 'cityName',
          children: 'cities'
        }
      }
    },
    methods: {
      handleItemChange(val) {
        let arr = val.toString().split(",")
        let id = arr[arr.length - 1]
        arr = []

        this.cityList.map((item, index) => {
          if (item.cityCode == id) {
            arr.push(index)
          } else {
            if (item.cities.length > 0) {
              item.cities.map((citem, cindex) => {
                if (citem.cityCode == id) {
                  arr.push(index)
                  arr.push(cindex)
                }
              })
            }
          }
        })
        fetchCitiesList(id).then(res => {
          res.data.map(item => {
            if (arr.length != 1) item.cities = []//这里可以控制层数
          })
          switch (arr.length) {
            case 0:
              break;
            case 1:
              this.cityList[arr[0]].cities = res.data
              break;
            case 2:
              this.cityList[arr[0]].cities[arr[1]].cities = res.data
              break;
          }
        })
      },
      dataBackfill (provincialCode, cityCode) {
        this.value = [provincialCode, cityCode]
        fetchCitiesList('0').then(res => {
          res.data.map(item => {
            item.cities = []
          })
          this.cityList = res.data
          let index
          this.cityList.forEach((item, i) => {
            item.cityCode === provincialCode && (index = i)
          })
          fetchCitiesList(provincialCode).then(res => {
            this.cityList[index].cities = res.data
          })
        })
      }
    },
    created() {
      fetchCitiesList('0').then(res => {
        res.data.map(item => {
          item.cities = []
        })
        this.cityList = res.data

      })
    }
  }
</script>

<style scoped>

</style>
